﻿using Microsoft.Extensions.Configuration;
using ServiceCore.Tool.Pic;
using ServiceCore.Tool.Post;
using System;
using System.Collections.Generic;
using System.Text;

namespace ServiceCore.Tool.MiniProgram
{
    public interface IMiniProgramApi
    {
        ResultObjModel get_Unlimited(string sceneParams);
        ResultObjModel code2Session(string code);
        /// <summary>
        /// 用户支付完成后，获取该用户的 UnionId，无需用户授权。。
        /// </summary>
        /// <param name="scene"></param>
        /// <returns></returns>
        ResultObjModel getPaidUnionId(string openid);
    }
    public class MiniProgramApi: IMiniProgramApi
    {
        
        private readonly IConfiguration AppSettingConfig;
        private readonly ICacheHelper _cache;
        public MiniProgramApi(IConfiguration configuration,ICacheHelper Cache)
        {
            AppSettingConfig = configuration;
            _cache = Cache;
        }
        public string appid { get { return AppSettingConfig["MiniProgram:appid"]; } }
        public string secret { get { return AppSettingConfig["MiniProgram:secret"]; } }
        /// <summary>
        /// 获取accesstoken
        /// </summary>
        /// <returns></returns>
        private ResultTModel<getAccessToken_Result> get_getAccessToken() {
            return CoreStartDo.ResultAction<ResultTModel<getAccessToken_Result>>(result =>
            {
                var MiniProgram_data = _cache.GetCache<getAccessToken_Result>("MiniProgramAccessToken");
                if (MiniProgram_data == null)
                {
                    string url = MiniProgramModel.Api_Url.getAccessToken + $"?grant_type=client_credential&appid={appid}&secret={secret}";
                    getAccessToken_Result wxresule = Newtonsoft.Json.JsonConvert.DeserializeObject<getAccessToken_Result>(Http_Helper.HttpGet(url));
                    if (wxresule.errcode == 0)
                    {
                        _cache.SetCache("MiniProgramAccessToken", wxresule, DateTimeOffset.Now.AddSeconds(wxresule.expires_in - 200));
                        result.code = 0;
                        result.msg = $"success";
                        result.data = wxresule;
                    }
                    else
                    {
                        result.code = 1;
                        result.msg = $"请求accesstoken异常=>{wxresule.errcode}=>{wxresule.errmsg}";
                    }
                }
                else
                {
                    result.code = 0;
                    result.msg = $"success";
                    result.data = MiniProgram_data;
                }
                return result;
            });
        } 
        /// <summary>
        /// 获取小程序二维码
        /// </summary>
        /// <param name="scene"></param>
        /// <returns></returns>
        public ResultObjModel get_Unlimited(string sceneParams) {
            return CoreStartDo.ResultAction(result =>
            {
                //获取accesstoken
                var accesstoken_model = get_getAccessToken();
                if (accesstoken_model.data.errcode != 0)
                {
                    result.code = 1;
                    result.msg = accesstoken_model.data.errmsg;
                    return result;
                }
                getUnlimited_Params Params = new getUnlimited_Params()
                { 
                    is_hyaline = true,
                    auto_color = true,
                    line_color = new { r = 56, g = 255, b = 0 },
                    scene = sceneParams,
                    page = "pages/index/index",
                    width = 1280
                };
                getUnlimited_Result post_result = Newtonsoft.Json.JsonConvert.DeserializeObject<getUnlimited_Result>(Http_Helper.HttpPost(MiniProgramModel.Api_Url.wxacode_getUnlimited+ "?access_token="+ accesstoken_model.data.access_token, Newtonsoft.Json.JsonConvert.SerializeObject(Params)));
                result.code = 0;
                result.msg = "success";
                result.data = post_result;
                return result;
            });
        }
        #region 登录
        /// <summary>
        /// 登录凭证校验。
        /// </summary>
        /// <param name="scene"></param>
        /// <returns></returns>
        public ResultObjModel code2Session(string code)
        {
            return CoreStartDo.ResultAction(result =>
            {
                //获取accesstoken
                string url = MiniProgramModel.Api_Url.auth_code2Session + $"?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code";
                code2Session_Result get_result = Newtonsoft.Json.JsonConvert.DeserializeObject<code2Session_Result>(Http_Helper.HttpGet(url));
                result.code = 0;
                result.msg = "success";
                result.data = get_result;
                return result;
            });
        }
        #endregion
        #region 用户信息
        /// <summary>
        /// 用户支付完成后，获取该用户的 UnionId，无需用户授权。。
        /// </summary>
        /// <param name="scene"></param>
        /// <returns></returns>
        public ResultObjModel getPaidUnionId(string openid)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(openid))
                {
                    result.code = 1;
                    result.msg = "openid不能为空";
                    return result;
                }
                //获取accesstoken
                var accesstoken_model = get_getAccessToken();
                if (accesstoken_model.data.errcode != 0)
                {
                    result.code = 1;
                    result.msg = accesstoken_model.data.errmsg;
                    return result;
                }
                //获取accesstoken
                string url = MiniProgramModel.Api_Url.getPaidUnionId + $"?access_token={accesstoken_model}&openid={openid}";
                getPaidUnionId_Result get_result = Newtonsoft.Json.JsonConvert.DeserializeObject<getPaidUnionId_Result>(Http_Helper.HttpGet(url));
                result.code = 0;
                result.msg = "success";
                result.data = get_result;
                return result;
            });
        }
        #endregion
    }
}
